// pages/ad-manage/ad-manage.ts

interface AdItem {
  id: number;
  imageUrl: string;
  remark: string;
  createTime: string;
  jumpLink: string;
  isEnabled: boolean;
}

interface NewAdForm {
  imageUrl: string;
  remark: string;
  jumpLink: string;
}

Page({
  data: {
    // 广告列表
    adList: [] as AdItem[],
    // 页面是否在初次加载
    isLoading: true,
    // 控制每个switch的切换状态
    isSwitching: {} as Record<number, boolean>,
    // 控制添加弹窗的显示
    showAddPopup: false,
    // 绑定新增表单的数据
    newAd: {
      imageUrl: '',
      remark: '',
      jumpLink: '',
    } as NewAdForm,
    // 控制提交按钮的加载状态
    isSubmitting: false,
  },

  onLoad() {
    this.fetchAdList();
  },

  /**
   * @description 获取广告列表数据 (模拟)
   */
  async fetchAdList() {
    this.setData({ isLoading: true });
    await new Promise(resolve => setTimeout(resolve, 1500));
    const mockData: AdItem[] = [
      { id: 101, imageUrl: 'https://img.yzcdn.cn/vant/cat.jpeg', remark: '年中大促！全场家具5折起！', createTime: '2023-10-26 10:30', jumpLink: '/pages/promo/summer-sale', isEnabled: true },
      { id: 102, imageUrl: 'https://img.yzcdn.cn/vant/cat.jpeg', remark: '新品上市：智能降噪耳机 Pro', createTime: '2023-10-25 15:00', jumpLink: '/pages/product/detail?id=9527', isEnabled: false },
    ];
    this.setData({ adList: mockData, isLoading: false });
  },

  /**
   * @description 切换广告可用状态
   */
  async onSwitchChange(e: WechatMiniprogram.CustomEvent) {
    const adId = e.currentTarget.dataset.id as number;
    const newStatus = e.detail.value as boolean;
    const adIndex = this.data.adList.findIndex(ad => ad.id === adId);
    if (adIndex === -1) return;

    this.setData({ [`isSwitching.${adId}`]: true });
    try {
      await new Promise(resolve => setTimeout(resolve, 1000));
      this.setData({ [`adList[${adIndex}].isEnabled`]: newStatus });
      wx.showToast({ title: '状态更新成功', icon: 'none' });
    } catch (error) {
      wx.showToast({ title: '操作失败，请重试', icon: 'none' });
    } finally {
      this.setData({ [`isSwitching.${adId}`]: false });
    }
  },

  /**
   * @description 删除广告项
   */
  onDelete(e: WechatMiniprogram.TouchEvent) {
    const adId = e.currentTarget.dataset.id as number;
    wx.showModal({
      title: '确认删除',
      content: '删除后广告将无法恢复，您确定吗？',
      confirmColor: '#f56c6c',
      success: async (res) => {
        if (!res.confirm) return;
        wx.showToast({ title: '删除中...', icon: 'loading', duration: 10000 });
        try {
          await new Promise(resolve => setTimeout(resolve, 1000));
          const newList = this.data.adList.filter(ad => ad.id !== adId);
          this.setData({ adList: newList });
          wx.hideToast();
          wx.showToast({ title: '删除成功', icon: 'none' });
        } catch (error) {
          wx.hideToast();
          wx.showToast({ title: '删除失败', icon: 'none' });
        }
      }
    });
  },

  /**
   * @description 打开添加弹窗
   */
  onAddAd() {
    this.setData({ showAddPopup: true });
  },

  /**
   * @description 关闭添加弹窗
   */
  onClosePopup() {
    this.setData({ 
      showAddPopup: false,
      newAd: { imageUrl: '', remark: '', jumpLink: '' },
      isSubmitting: false,
    });
  },

  /**
   * @description 监听输入框变化
   */
  onFieldChange(e: WechatMiniprogram.CustomEvent) {
    const { field } = e.currentTarget.dataset;
    this.setData({ [`newAd.${field}`]: e.detail });
  },

  /**
   * @description 选择广告图片
   */
  onChooseImage() {
    wx.chooseMedia({
      count: 1, mediaType: ['image'], sourceType: ['album', 'camera'],
      success: (res) => {
        const tempFilePath = res.tempFiles[0].tempFilePath;
        this.setData({ 'newAd.imageUrl': tempFilePath });
      },
      fail: (err) => {
        if (err.errMsg.indexOf('cancel') === -1) {
            wx.showToast({ title: '选择图片失败', icon: 'none' });
        }
      }
    });
  },

  /**
   * @description 提交新增的广告
   */
  async onSubmitAd() {
    const { newAd } = this.data;
    if (!newAd.imageUrl) {
      return wx.showToast({ title: '请上传广告图片', icon: 'none' });
    }
    if (newAd.jumpLink && !/^https?:\/\//.test(newAd.jumpLink)) {
      return wx.showToast({ title: '链接请以http/https开头', icon: 'none' });
    }

    this.setData({ isSubmitting: true });
    try {
      wx.showToast({ title: '正在添加...', icon: 'loading', duration: 10000 });
      await new Promise(resolve => setTimeout(resolve, 1500));

      const newAdItem: AdItem = {
        id: Date.now(),
        imageUrl: newAd.imageUrl,
        remark: newAd.remark || '暂无备注',
        createTime: new Date().toLocaleString('zh-CN', { hour12: false }).replace(/\//g, '-'),
        jumpLink: newAd.jumpLink || '无',
        isEnabled: true,
      };
      
      this.setData({ adList: [newAdItem, ...this.data.adList] });
      wx.hideToast();
      wx.showToast({ title: '添加成功', icon: 'none' });
      this.onClosePopup();
    } catch (error) {
      wx.hideToast();
      wx.showToast({ title: '添加失败，请重试', icon: 'none' });
    } finally {
      this.setData({ isSubmitting: false });
    }
  },

  /**
   * @description 下拉刷新
   */
  onPullDownRefresh() {
    this.fetchAdList().then(() => {
      wx.stopPullDownRefresh();
      wx.showToast({ title: '刷新成功', icon: 'none' });
    });
  }
});
